package com.mumulx.check.scheduler;


import com.mumulx.check.model.SubmitFileRecord;
import com.mumulx.check.model.SubmitRecord;
import com.mumulx.check.redis.entity.CheckPartContants;
import com.mumulx.check.redis.entity.PartTestBoxed;
import com.mumulx.check.model.CheckpartSendLog;
import com.mumulx.check.redis.RedisKeyType;
import com.mumulx.check.redis.RedisUtil;
import com.mumulx.check.service.service.CheckpartSendLogService;
import com.mumulx.check.service.service.SubmitFileRecordService;
import com.mumulx.check.service.service.SubmitRecordService;
import com.mumulx.check.service.service.SubmitRuleRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
 *  Created by IntelliJ IDEA.
 *  User: 木木
 *  Date: 2020/10/23
 *  Time: 13:58
 * 定时任务
 */
@Component
@Slf4j
public class SchedulerTask {
    @Resource
    RedisUtil redisUtil;
    @Resource
    CheckpartSendLogService checkpartSendLogService;

    /*
     *
     * @author mumulx
     * @creed: mumulx编写
     * @email: 2606964863@qq.com
     * @date 2020/10/23 13:59
     * @param
     * @return void
     * 每6小时执行一次 将结果放到redis中
     */
    @Scheduled(fixedRate = 21600000)
    //@Cacheable("loveTalk")
    public void process() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://chp.shadiao.app/api.php";
        LinkedMultiValueMap<String, String> lv = new LinkedMultiValueMap<>();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String body = responseEntity.getBody();
        body.replaceAll(" ", "<br/>");
        redisUtil.set(RedisKeyType.TALK_LOVE.getKey(), body);
        log.info("-------定时任务开启：" + body);
    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Resource
    SubmitRecordService submitRecordService;
    @Resource
    SubmitFileRecordService submitFileRecordService;
    @Resource
    SubmitRuleRecordService submitRuleRecordService;


    /*
     * 用于重试消息发送
     * @author mumulx
     * @creed: mumulx编写
     * @email: 2606964863@qq.com
     * @date 2020/11/4 9:52
     * @param
     * @return void
     * 1分钟执行一次
     */
    @Scheduled(fixedRate = 60000)
    public void mailResendTask() {
        log.info("消息重发定时任务开启");
        List<CheckpartSendLog> CheckpartSendLogs = checkpartSendLogService.getMailSendLogsByStatus();
        CheckpartSendLogs.forEach(checkpartSendLog -> {
            log.info("重试发送消息");
            /**当超过重试次数后会标记消息发送失败--不再重复发送消息*/
            if (checkpartSendLog.getCount() >= CheckPartContants.MAX_TRY_COUNT) {
                log.info("消息重试次数过多---消息发送失败");
                checkpartSendLogService.updateMailSendLogStatus(checkpartSendLog.getMsgId(), 2);//直接设置该条消息发送失败
            } else {
                log.info("准备发送消息");
                checkpartSendLogService.updateCount(checkpartSendLog.getMsgId(), new Date());
                Integer srId = checkpartSendLog.getSrId();

                //获取需要重发消息的  测试记录
                SubmitRecord submitRecord = submitRecordService.queryRecordBySrId(srId);
                //获取prts
                Map<Integer, String> parts = submitFileRecordService.queryFileRecordListBysrid(srId).stream().collect(Collectors.toMap(SubmitFileRecord::getSfrId, SubmitFileRecord::getSfrFileName));
                //获取rules
                List<String> rules = submitRuleRecordService.queryCheckerListBySrId(srId);
                //对象包装
                PartTestBoxed partTestBoxed = new PartTestBoxed();
                partTestBoxed.setUserId(submitRecord.getSrUserId());
                partTestBoxed.setParts(parts);
                partTestBoxed.setRules(rules);
                partTestBoxed.setTestRecordId(srId);
                log.info("重发的消息的基本信息："+partTestBoxed.toString());
                //重新发送消息
                rabbitTemplate.convertAndSend(CheckPartContants.MAIL_EXCHANGE_NAME, CheckPartContants.MAIL_ROUTING_KEY_NAME, partTestBoxed, new CorrelationData(checkpartSendLog.getMsgId()));
                log.info("消息重发成功");
            }
        });
    }

    /*
     * 用于删除 测试记录---保存时间默认为30天
     * @author mumulx
     * @creed: mumulx编写
     * @email: 2606964863@qq.com
     * @date 2020/11/6 16:16
     * @param
     * @return void
     */
    @Scheduled(fixedRate = 1800000)
    public void deleteSubmitRecordByexpiredTime() {
        List<Integer> srIds = submitRecordService
                .queryExpiredTimeList()
                .stream()
                .mapToInt(e -> e.getSrId())
                .boxed()
                .collect(Collectors.toList());
        //删除 测试规则记录信息
        srIds.forEach(srId->{
            log.info("检测到有测试记录要删除---已过期：srid="+srId);
            //删除测试文件记录信息--删除文件服务器上的文件--删除数据库中的数据
            submitFileRecordService.deleteFileRecordBySrId(srId);
            //删除测试规则记录信息
            submitRuleRecordService.deleteRuleRecordBySrId(srId);
            //删除测试记录
            submitRecordService.deleteRecordBySrId(srId);
            log.info(srId+"记录删除成功");

        });
    }


}
